#include "nodeitem.h"

NodeItem::NodeItem(qreal ax, qreal ay, qreal w, qreal h)//:QGraphicsEllipseItem(QRectF(ax, ay, w, h))
{

    setRect(-w/2,-h/2,w,h);
    setPos(QPointF( ax,  ay));

    // qDebug() << ax << ay << pos() << scenePos();
    // qDebug() << mapToScene(pos()) << mapToScene(scenePos());
    // qDebug() << mapFromScene(pos()) << mapFromScene(scenePos());

    initNode();

    // qDebug() << ax << ay << pos() << scenePos();
}





void NodeItem::initNode()
{
    //setCacheMode(QGraphicsItem::ItemCoordinateCache);
    setFlag(QGraphicsItem::ItemIsMovable);
    setBrush(QBrush(Qt::yellow));
    setZValue(10);
    //setPos(mapToScene(pos()));
    setAcceptHoverEvents(true);
    stateType = sleepState;

    pen_def     = QPen(QColor( 0, 0, 0,255), 2,  Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
    pen_current = QPen(QColor( 0, 0, 0,255), 4,  Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
    pen_hover   = QPen(QColor(90, 0,90,200), 8,  Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);

    setPen(pen_def);
}


void NodeItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        stateType = mPress;
    }
    QGraphicsEllipseItem::mousePressEvent(event);
}

void NodeItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    stateType = sleepState;
    QGraphicsEllipseItem::mouseReleaseEvent(event);
}

void NodeItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if(stateType == mPress){
        updateEdge();
    }
    QGraphicsEllipseItem::mouseMoveEvent(event);
}

void NodeItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
    setPen(pen_hover);

    QGraphicsEllipseItem::hoverEnterEvent(event);
}

void NodeItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
{

    if(connectEdges.length()>0){
        setPen(pen_current);
    }else{
        setPen(pen_def);
    }
    QGraphicsEllipseItem::hoverLeaveEvent(event);
}

NodeItem::~NodeItem()
{

}

void NodeItem::addEdge(EdgeItem *edge)
{
    connectEdges.append(edge);
    setPen(pen_current);

}

EdgeItem *NodeItem::getEdge(quint32 toIndex)
{
    foreach(EdgeItem *edge, connectEdges){
        if(edge->getNodeOther(this)->getIndex() == toIndex){
            return edge;
        }
    }
}

void NodeItem::removeEdge(EdgeItem *edge)
{
    //connectEdges.re
}

void NodeItem::updateEdge()
{
    foreach(EdgeItem *edge, connectEdges){
        edge->updatePosition();
    }
}

quint32 NodeItem::getIndex()
{
  return nodeIndex;
}

void NodeItem::setIndex(quint32 indx)
{
    nodeIndex = indx;
}

void NodeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter-> setRenderHint (QPainter:: Antialiasing);
    QGraphicsEllipseItem::paint(painter, option, widget);
}


